<template>
<canvas 
    id="canvas" 
    :width="canvasW" 
    :height="canvasH" 
    ref="canvas"
></canvas>
</template>

<script>
export default {
    name: 'myCanvasDrawImage',
    props: {
        fileinfo: {
            required: true
        },
        draw: {
            required: true,
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            // canvas
            canvasW: 200,
            canvasH: 100,
            // 预览图
            imageW: 0,
            imageH: 0,
            scaleNum: 1 /* 缩放比例 */
        }
    },
    methods: {
        getFileData() {
            let fileReader = new FileReader()
            fileReader.readAsDataURL(this.fileinfo)
            fileReader.onload = e => {
                let prew = new Image()
                prew.src = e.target.result /* baase64 */
                prew.onload = _ => {
                    this.imageW = prew.width
                    this.imageH = prew.height
                    if(this.imageW > this.imageH) {
                        this.scaleNum = this.imageW / this.canvasW
                        this.imageW = this.canvasW
                        this.imageH = this.imageH / this.scaleNum
                    } else {
                        this.scaleNum = this.imageH / this.canvasH
                        this.imageH = this.canvasH
                        this.imageW = this.imageW / this.scaleNum
                    }
                    this.drawImg(prew)
                }
            }
        },
        drawImg(prew) {
            // 创建画布
            this.cdx = this.$refs.canvas.getContext('2d')
            // 清空画布
            this.cdx.clearRect(0, 0, this.imageW, this.imageH)
            // 绘制图片
            this.cdx.drawImage(
                prew, 
                0, 
                0,
                this.imageW, 
                this.imageH
            )
        }
    },
    watch: {
        'draw'(val) {
            if(val) {
                this.getFileData()
            }
        }
    }
}
</script>

<style scoped>

</style>